package server

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"plan_go/config"
	"plan_go/dm"
	"plan_go/server/util"
	"strings"
	"time"
)

func StartDmServer() {
	dll := dm.GetDm("main")
	r := gin.Default()

	r.GET("/sovits/convert", func(c *gin.Context) {
		audioPath := c.Query("filePath")
		SovitsConvert(audioPath)
		c.JSON(200, gin.H{
			"message": "转换完成!",
		})
	})

	r.GET("/call", func(c *gin.Context) {
		asmArray := c.QueryArray("asmArray")
		asmCall := "pushad\nmov ecx,dword ptr [6A9EC0]\nmov ecx,dword ptr [ecx+768]\npush -1\npush 2\nmov eax,3\npush 8\npush ecx\ncall 0040D120\npopad\nret"
		asmArray = strings.Split(asmCall, "\n")
		hwnd := dll.FindWindow("MainWindow", "植物大战僵尸中文版")
		println(fmt.Sprintf("hwnd: %d", hwnd))
		c.JSON(200, gin.H{
			"message": dll.AsmCallOrder(hwnd, 1, asmArray),
		})
	})

	/**dm点击windows窗口程序控件*/
	type ModuleTrigger struct {
		Class string `json:"Class"`
		Title string `json:"title"`
		//控件顺序
		WindowOrder []int `json:"windowOrder"`
	}
	// 处理POST请求
	r.POST("/moduleTrigger", func(c *gin.Context) {
		// 获取请求Body中的数据
		var moduleTrigger ModuleTrigger
		if err := c.ShouldBindJSON(&moduleTrigger); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		hwnd := dm.GetDm("main").GetTargetWindow(moduleTrigger.Class, moduleTrigger.Title, moduleTrigger.WindowOrder)
		if 0 == hwnd {
			dm.GetDm("main").RunApp(config.GetConfig().Uvr5Path, 0)
			time.Sleep(5 * time.Second)
		}
		//WorkOnWindow(hwnd, func() {
		//	//input按钮
		//	dm.GetDm("main").MoveAndLeftClick(10,10)
		//})
		c.JSON(http.StatusOK, gin.H{
			"message": hwnd,
		})
	})

	r.GET("/write", func(c *gin.Context) {
		yaml, _ := util.ReadYAML("config.yaml")
		c.JSON(200, gin.H{
			"message": yaml,
		})
	})

	r.GET("/test", func(c *gin.Context) {
		go func() {
			for {
				log.Println("test")
				time.Sleep(1 * time.Second)
			}
		}()
	})

	r.Run(":54321") //默认80端口，可通过 r.Run(":8888")改为8888端口
}

func ExitServer() {
	dm.ExitDm()
}
